import pylink
import binascii


class JLinkProgram(object):
    def __init__(self):
        self.jlk = pylink.JLink(lib=pylink.library.Library(dllpath='JLink_x64.dll'))

    def get_jlkserialnum(self):
        jlk_list = []
        pjlist = self.jlk.connected_emulators()
        for item in pjlist:
            jlk_list.append(str(item.SerialNumber))
        return jlk_list

    def jlk_connect(self, jlkserialnum, device, interface, speed):
        self.jlk.open(jlkserialnum)
        if interface == "SWD":
            self.jlk.set_tif(pylink.enums.JLinkInterfaces.SWD)
        else:
            self.jlk.set_tif(pylink.enums.JLinkInterfaces.JTAG)
        self.jlk.connect(device, speed=int(speed))

    def write_flash(self, file, addr, progress):
        self.jlk.flash_file(file, addr, on_progress=progress)

    def GetMcuInfo(self):
        ARM_Id = self.jlk.core_id()
        CPU_Id = self.jlk.core_cpu()
        Core_Name = self.jlk.core_name()
        Device_Family = self.jlk.device_family()
        return [ARM_Id, CPU_Id, Core_Name, Device_Family]

    def jlk_erase(self):
        self.jlk.erase()

    def jlk_read(self, addr, size):
        mem = self.jlk.memory_read8(addr, size)
        mem_byte = bytearray(mem)
        mem_ascii = binascii.b2a_hex(mem_byte)
        return mem_ascii
